package com.cold.demo.rabbitmq.demo2.$6.rpc;

import com.cold.demo.rabbitmq.utils.ConnectionUtils;
import com.rabbitmq.client.*;

import java.nio.charset.StandardCharsets;

public class RPCServer {

    private static final String RPC_QUEUE_NAME = "rpc_queue";

    private static int fib(int n) {
        if (n == 0) return 0;
        if (n == 1) return 1;
        return fib(n - 1) + fib(n - 2);
    }

    public static void main(String[] argv) throws Exception {

        try (
                Connection connection = ConnectionUtils.getConnection();
                Channel channel = connection.createChannel()
        ) {
            channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
            channel.queuePurge(RPC_QUEUE_NAME);

            channel.basicQos(1);


            Object monitor = new Object();
            DeliverCallback deliverCallback = (consumerTag, delivery) -> {
                // 接收来自请求端的properties
                AMQP.BasicProperties replyProps = new AMQP.BasicProperties.Builder().correlationId(delivery.getProperties().getCorrelationId()).build();

                String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
                System.out.println("接收到的消息：" + message);

                String response = "酸辣粉和切完辣椒怕是";
                // 返回消息
                String replyQueueName = delivery.getProperties().getReplyTo();
                channel.basicPublish("", replyQueueName, replyProps, response.getBytes(StandardCharsets.UTF_8));
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                // RabbitMq consumer worker thread notifies the RPC server owner thread
                synchronized (monitor) {
                    monitor.notify();
                }
            };


            channel.basicConsume(RPC_QUEUE_NAME, false, deliverCallback, (consumerTag -> {
            }));


            while (true) {
                synchronized (monitor) {
                    try {
                        monitor.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}